package com.everflourish.yeah100.act.markingsystem;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.act.statistics.TeacherStatisticsActivity;
import com.everflourish.yeah100.adapter.FragmentStudentAdapter;
import com.everflourish.yeah100.entity.Examination;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.marking.ReadCardRecord;
import com.everflourish.yeah100.entity.marking.Standard;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.entity.marking.StudentAnswersLastModifiedTime;
import com.everflourish.yeah100.entity.marking.StudentModel;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.http.ExaminationRequest;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.ui.dialog.ReadCardInfoDialog;
import com.everflourish.yeah100.utils.AnswerUtil;
import com.everflourish.yeah100.utils.DateFormatUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.JsonUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.collections.TopicCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.RecordType;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;
import com.everflourish.yeah100.utils.constant.StudentStatus;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 作者：Created by liqisi on 2016/6/3.
 * 时间：2016/6/3
 */
public class FragmentReadPaper extends BaseFragment implements View.OnClickListener {

    private List<StudentModel> mList;
    public MarkingMenuActivity mMarkingMenuActivity;
    private MarkingSystemRequest mRequest;
    private ExaminationRequest mExaminationRequest;
    public FragmentStudentAdapter mAdapter;
    private RecyclerView mStudnetList;
    private TextView mSubScoreTv, mStuSureTv, mRefreshTv;
    public Button mStuReadCardBt;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    public ArrayList<Topic> mTopics;
    public List<ClassManage> mClassManages;
    // 数据是否被更改，锁
    public boolean isDataChange = false;
    public Map<String, Student> mStudentMap = new HashMap<>();
    private PaperType mEPaperType = PaperType.NONE;
    public ArrayList<Map<String, Object>> mStaList;
    // 是否刷新：当基础信息，题型修改后isRefresh = true;
    private boolean isRefresh = false;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    private boolean isFirstRefresh = true;
    private FrameLayout mRefreshFl;
    private ReadCardInfoDialog mReadCardInfoDialog;
    private AlertDialog mConnectedDialog;
    public List<ReadCardRecord> mRecordList;
    // 上传的student
    public Student mStudent;
    // 备份上传之前的数据
    public Student mBackupStudent;
    private boolean isSingleUpload = false;
    // 是否是单个上传，如果为true表示是在学生客观题界面上保存上传
    private boolean isSingleUploadOfLoading = false;
    public LinkedList<Student> uploadStudents = new LinkedList<Student>();
    private Context mContext;
    // 是否是手动输入客观题答案
    public boolean isObjectOrSubjectInput = false;

    /**
     * 如果有上传失败的学生，则为true，否则为false
     */
    public boolean isUploadStudentAnswers = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_student_answer, container,
                false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initWidget();
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        configWidget();
        isPrepared = false;
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        isRefresh = true;
        mClassManages = null;
        if (isVisible()) {
//            mRefreshListener.onRefresh();
            configWidget();
        }
        isFirstRefresh = false;
    }

    private void initData() {
        mList = new ArrayList<StudentModel>();
        mStaList = new ArrayList<Map<String, Object>>();
        mContext = mMarkingMenuActivity = (MarkingMenuActivity) getActivity();
        mRequest = MarkingSystemRequest.getInstance();
        mExaminationRequest = ExaminationRequest.getInstance();
        mAdapter = new FragmentStudentAdapter(mContext, mList, this);
        mRecordList = new ArrayList<ReadCardRecord>();
    }

    private void initWidget() {
        mStudnetList = (RecyclerView) getView().findViewById(R.id.student_list_rv);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.student_answer_swipe);
        mSubScoreTv = (TextView) getView().findViewById(R.id.e_student_sub_score);
        mStuReadCardBt = (Button) getView().findViewById(R.id.student_read_bt);
        mStuSureTv = (TextView) getView().findViewById(R.id.student_upload_sure);
        mStuReadCardBt.setOnClickListener(this);
        mStuSureTv.setOnClickListener(this);
        mRefreshFl = (FrameLayout) getView().findViewById(R.id.topic_refresh_fl);
        mRefreshTv = (TextView) getView().findViewById(R.id.include_refresh_tv);
        mRefreshTv.setTextColor(mContext.getResources().getColor(R.color.marking_appbar_primaryDark));
        mRefreshTv.setOnClickListener(this);
    }

    @SuppressWarnings("ResourceType")
    private void configWidget() {
        mStudnetList.setAdapter(mAdapter);
        mStudnetList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getStudentAnswersRequest();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.student_read_bt:
                if (mList == null || mList.size() == 0) {
//                    MyToast.showShort(mContext, "请先刷新！");
                    return;
                }
                readCard(1, true);
                break;
            case R.id.student_upload_sure:
//                if (isUploadStudentAnswers) {
//                    uploadStudentAnswerRequest(mClassManages);
//                }
                if (Yeah100.mRoleEnum == RoleEnum.TEACHER
                        && mMarkingMenuActivity.mExamination.getStatisticTiggered().equals("N")) {
                    statisticRequest(mMarkingMenuActivity.mExamination);
                } else {
//                    Intent statisticsIntent = new Intent(mMarkingMenuActivity,
//                            TeacherStatisticsActivity.class);
                    Intent statisticsIntent = new Intent();
                    statisticsIntent.putExtra(IntentUtil.EXAMINATION, mMarkingMenuActivity.mExamination);
                    statisticsIntent.setClass(mMarkingMenuActivity, TeacherStatisticsActivity.class);
                    mMarkingMenuActivity.startActivity(statisticsIntent);
//                    mMarkingMenuActivity.startActivity(statisticsIntent);
                }
                break;
        }
    }

    /**
     * 统计成绩请求
     *
     * @param examination
     */
    public void statisticRequest(final Examination examination) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在统计中...", mQueue);
        JsonObjectRequest request = mExaminationRequest.executeStatisticJob(examination.getId(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        statisticListener(response, examination);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mExaminationRequest.disposeError(mContext, mLoadDialog, error, "统计学生成绩失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 发布考试请求
     *
     * @param examination
     */
    private void publishRequest(final Examination examination) {
        // 发布考试
        JsonObjectRequest request = mExaminationRequest.publishExaminationRequest(examination.getId(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        publishListener(jsonObject, examination);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        LogUtil.e("发布考试发生异常", volleyError);
                        mExaminationRequest.disposeError(mContext, mLoadDialog, volleyError, "统计学生成绩失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 统计成绩监听
     *
     * @param response
     */
    private void statisticListener(JSONObject response, Examination examination) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                publishRequest(examination);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07092_000012E);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07091_000001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07093_300001E);
            } else if (resultCode.equals(ResultCode.result_300020E.resultCode)) {
                String errorMsg = response.getString("errorMessage");
                MyToast.showShort(mContext, errorMsg);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_070999_999999E);
            } else {
                MyToast.showShort(mContext, "统计学生成绩失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            e.printStackTrace();
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                LoadDialog.dismiss(mLoadDialog);
            }
        }
    }

    /**
     * 发布考试监听
     *
     * @param response
     * @param examination
     */
    private void publishListener(JSONObject response, Examination examination) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                examination.setStatisticTiggered("Y");
                examination.setStatus("1");
                mMarkingMenuActivity.isUpdateExamination = true;
                Intent intent = new Intent();
                intent.putExtra(IntentUtil.EXAMINATION, examination);
                intent.setClass(mMarkingMenuActivity, TeacherStatisticsActivity.class);
                mMarkingMenuActivity.startActivity(intent);
                MyToast.showShort(mContext, "统计成绩成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07101_000001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07102_300001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07103_000012E);
            } else if (resultCode.equals(ResultCode.result_300015E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_07104_300015E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showLong(mContext, R.string.readcard_071099_999999E);
            } else {
                MyToast.showLong(mContext, "统计成绩失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showLong(mContext, "统计成绩失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }


    /**
     * 开启学生读卡操作
     *
     * @param index      1 学生列表界面 2 详细界面
     * @param isReadCard 是否开启读卡操作，如果已经连接，false不影响
     */
    public void readCard(int index, boolean isReadCard) {
        if (mMarkingMenuActivity.mBluetoothHelper.isConn) {// 如果已经连接蓝牙，切换为等待读卡卡状态
            mStuReadCardBt.setText("等待读卡...");
            mMarkingMenuActivity.mReadFlag = mMarkingMenuActivity.STUDENT_FLAG;
        } else {// 未连接蓝牙，提示是否连接蓝牙
            if (isReadCard) {
                mMarkingMenuActivity.openBluetooth();
            } else {
                mStuReadCardBt.setText("读卡");
                mMarkingMenuActivity.mReadFlag = mMarkingMenuActivity.NOT_READ_FLAG;
            }
        }
    }

    /**
     * 获取学生答案请求
     */
    public void getStudentAnswersRequest() {
        isRefresh = false;
        mStuReadCardBt.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.getAggregateRequest(
                mMarkingMenuActivity.mExamination.getId(), true, true, true,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getStudentAnswerExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (!isObjectOrSubjectInput) {
                            mRequest.disposeError(mContext, mLoadDialog, error, "获取学生答案失败");
                        }
                        isObjectOrSubjectInput = false;
                        mSwipeRefreshLayout.setRefreshing(false);
                        mStuReadCardBt.setVisibility(View.GONE);
                        mList = null;
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取学生答案监听
     *
     * @param response
     */
    public void getStudentAnswerExaminationListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                // 获取题型
                mTopics = AnswerUtil.getTopics(response);
                // 获取考试最后的修改时间
                mMarkingMenuActivity.mExamination.setLastModifiedTime(JsonUtil
                        .getLastModifiedTime(response, null));
                // 获取标准答案
                List<Standard> standards = AnswerUtil
                        .getStandardAnswers(response);
                setAnswers(standards);
                if (mStaList == null) {
                    MyToast.showShort(mContext, "当前还未设置标准答案，请先设置标准答案！");
                    return;
                }
                // 获取学生的答案
                mClassManages = AnswerUtil.getStudentAnswers(response);
                // 为判断锁做准备
                mStudentMap.clear();
                for (ClassManage c : mClassManages) {
                    for (Student s : c.getStudents()) {
                        mStudentMap.put(s.getId(), s);
                    }
                }
                setListData(mClassManages);
                if (isDataChange) {
                    if (!mMarkingMenuActivity.mFragmentReadPaper.isHidden()) {
                        boolean isBreak = false;
                        for (ClassManage m : mClassManages) {
                            for (Student s : m.getStudents()) {
                                if (s.getId().equals(mMarkingMenuActivity.mFragmentReadPaper.mStudent
                                        .getId())) {
                                    mStudent = s;
                                    isBreak = true;
                                    break;
                                }
                            }
                            if (isBreak) {
                                break;
                            }
                        }
                    }
                }
                if (isObjectOrSubjectInput) {
                    if (!mMarkingMenuActivity.mFragmentReadPaper.isHidden()) {
                        boolean isBreak = false;
                        for (ClassManage m : mClassManages) {
                            for (Student s : m.getStudents()) {
                                if (ObjectAnswerActivity.mStudent != null) {
                                    if (s.getId().equals(ObjectAnswerActivity.mStudent
                                            .getId())) {
                                        ObjectAnswerActivity.mStudent = s;
                                        isBreak = true;
                                        break;
                                    }
                                } else if (SubjectAnswerActivity.mStudent != null) {
                                    if (s.getId().equals(SubjectAnswerActivity.mStudent
                                            .getId())) {
                                        SubjectAnswerActivity.mStudent = s;
                                        isBreak = true;
                                        break;
                                    }
                                }
                            }
                            if (isBreak) {
                                break;
                            }
                        }
                    }
                }
//                setIsAllUploadSucess();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07081_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07082_000012E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07083_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070899_999999E);
            } else {
                MyToast.showShort(mContext, "获取学生答案失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取学生答案失败");
        } finally {
            isObjectOrSubjectInput = false;
            isDataChange = false;
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    /**
     * 设置学生答案list
     *
     * @param classManages
     */
    private void setListData(List<ClassManage> classManages) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
            if (!TopicUtil.isHaveSubTopic(mTopics)) {
                mSubScoreTv.setVisibility(View.GONE);
            } else {
                mSubScoreTv.setVisibility(View.VISIBLE);
            }
        }
        if (mList == null) {
            mList = new ArrayList<StudentModel>();
        }
        mList.clear();
        for (ClassManage c : classManages) {
            ArrayList<Student> students = c.getStudents();
            for (Student s : students) {
                StudentModel studentModel = new StudentModel();
                studentModel.setStudent(s);
                studentModel.setClassName(c.getName());
                mList.add(studentModel);
            }
        }
    }

    /**
     * 设置标准答案list
     *
     * @param standards
     */
    private void setAnswers(List<Standard> standards) {
        Collections.sort(mTopics, new TopicCollections(false));
        if (standards == null) {
            return;
        }
        if (mEPaperType == PaperType.NONE) { // 没有分AB卷
            ArrayList<Map<String, Object>> answerList = null;
            if (standards != null && standards.size() > 0) {
                answerList = AnswerUtil.answerToStudentList(standards.get(0)
                        .getContent(), mTopics);
            } else {
                answerList = AnswerUtil.answerToStudentList(null, mTopics);
            }
            mStaList.clear();
            mStaList.addAll(answerList);
        }
    }

    /**
     * 上传学生答案请求
     *
     * @param classManages
     */
    public void uploadStudentAnswerRequest(List<ClassManage> classManages) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在上传...", mQueue);
        isSingleUpload = false;
        JsonObjectRequest request = mRequest.uploadStudentAnswersRequest(
                mMarkingMenuActivity.mExamination.getId(),
                mMarkingMenuActivity.mExamination.getLastModifiedTime(),
                classManages, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        uploadStudentAnswerExaminationListener(response, "3");
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                        isBackAndSave = false;
//                        setIsAllUploadSucess();
                        if (isSingleUpload) {
                            Student uploadStudent = uploadStudents.getFirst();
                            uploadStudent
                                    .setUploadStatus(FragmentStudentAdapter.UPLOAD_FAILURE);
                            mAdapter.notifyDataSetChanged();
                            uploadStudents.removeFirst();
                        } else {
                            mRequest.disposeError(mContext, mLoadDialog, error, "提交学生答案失败");
                            mRequest.disposeError(mContext, ObjectAnswerActivity.mLoadDialog, error, "提交学生答案失败");
                            mRequest.disposeError(mContext, SubjectAnswerActivity.mLoadDialog, error, "提交学生答案失败");
                        }
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }


    /**
     * 上传单个学生答案请求
     *
     * @param student
     * @param isShowDialog
     * @param isObjectAnswer 1、客观题  2、主观题
     *                       是否显示对话框
     */
    public void uploadSingleStudentAnswerRequest(final Student student,
                                                 final boolean isShowDialog, final String isObjectAnswer, final boolean isAuto) {
        new AsyncTask<Void, Void, Void>() {
            Student tempStudent = null;

            @Override
            protected void onPreExecute() {
                tempStudent = student;
                isSingleUploadOfLoading = isShowDialog;
                if (isShowDialog) {
                    mLoadDialog = LoadDialog.show(mContext, null, "正在保存...", false, null);
                }
                tempStudent.setUploadStatus(FragmentStudentAdapter.UPLOADING);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            protected synchronized Void doInBackground(Void... params) {
                while (uploadStudents.size() > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (mTopics == null || mTopics.size() == 0) {
                    showPromt();
                    return;
                }
                isSingleUpload = true;
                uploadStudents.add(tempStudent);
                if (TextUtils.isEmpty(tempStudent.getAnswer()
                        .getObjectAnswers())) {
                    tempStudent.getAnswer().setObjectAnswers(AnswerUtil
                            .topicsToAnswerContent(mTopics));
                }
//                if (isObjectOrSubjectInput) {
//                    MyToast.showShort(mContext, mMarkingMenuActivity.mExamination.getLastModifiedTime());
//                    String modifiedTime = DateFormatUtil.convertMillisecondsToStr(System.currentTimeMillis(), "yyyy-MM-dd hh:mm:ss");
//                    MyToast.showShort(mContext, System.currentTimeMillis() + "");
//                    mMarkingMenuActivity.mExamination.setLastModifiedTime(modifiedTime);
//                }
                JsonObjectRequest request = mRequest
                        .uploadSingleStudentAnswersRequest(
                                mMarkingMenuActivity.mExamination.getId(),
                                mMarkingMenuActivity.mExamination
                                        .getLastModifiedTime(), mClassManages,
                                tempStudent, new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        uploadStudentAnswerExaminationListener(response, isObjectAnswer);
                                    }
                                }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(
                                            VolleyError error) {
                                        uploadStudentAnswerExaminationErrorListener(error, isObjectAnswer);
                                    }
                                });
                mQueue.add(request);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }


    /**
     * 学生答案是否全部上传成功
     *
     * @return true已经全部上传成功，否则不是
     */
    private boolean setIsAllUploadSucess() {
        boolean isAllUploadSucess = true;
        for (StudentModel studentModel : mList) {
            Student s = studentModel.getStudent();
            if (s.getUploadStatus() == null) {
                continue;
            }
            if (s.getUploadStatus() == FragmentStudentAdapter.UPLOAD_FAILURE
                    || s.getUploadStatus() == FragmentStudentAdapter.UPLOADING) {
                isAllUploadSucess = false;
                break;
            }
        }
        isUploadStudentAnswers = !isAllUploadSucess;
        return isAllUploadSucess;
    }

    private void showPromt() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("您当前还未设置题型，请先设置题型");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 上传学生答案监听
     *
     * @param response
     */
    private void uploadStudentAnswerExaminationListener(JSONObject response, String isObjcetAnswer) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                if (isSingleUpload) {
                    Student uploadStudent = uploadStudents.getFirst();
                    uploadStudent.setUploadStatus(FragmentStudentAdapter.COMPLETE);
                    uploadStudents.removeFirst();
                    mAdapter.notifyDataSetChanged();
                    if (isSingleUploadOfLoading) {
                        if (isObjcetAnswer.equals("1")) {
                            MyToast.showShort(mContext, "保存学生答案成功");
                        } else if (isObjcetAnswer.equals("2")) {
                            MyToast.showShort(mContext, "录入学生分数成功");
                        } else if (isObjcetAnswer.equals("3")) {
                            MyToast.showShort(mContext, "上传学生答案成功");
                        }
                    }
//                    setIsAllUploadSucess();
                } else {
                    // 如果一键提交成功后，移除所有上传中的student
                    for (ClassManage c : mClassManages) {
                        for (Student s : c.getStudents()) {
                            if (s.getUploadStatus() == null
                                    || s.getUploadStatus() != FragmentStudentAdapter.UPLOAD_FAILURE
                                    && s.getUploadStatus() != FragmentStudentAdapter.UPLOADING) {
                                continue;
                            }
                            s.setUploadStatus(FragmentStudentAdapter.COMPLETE);
                        }
                    }
                    mAdapter.notifyDataSetChanged();
//                    setIsAllUploadSucess();
//                    statisticJob();
                }
                // 统计总人数和参考数
                mMarkingMenuActivity.isUpdateExamination = true;
                // 修改学生的最后修改时间
                List<StudentAnswersLastModifiedTime> studentAnswersLastModifiedTimes = null;
                if (response == null
                        || response.isNull("studentAnswersLastModifiedTimes")) {
                    studentAnswersLastModifiedTimes = new ArrayList<StudentAnswersLastModifiedTime>();
                } else {
                    JSONArray jsonArray = response
                            .getJSONArray("studentAnswersLastModifiedTimes");
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<StudentAnswersLastModifiedTime>>() {
                    }.getType();
                    studentAnswersLastModifiedTimes = gson.fromJson(
                            jsonArray.toString(), type);
                }
                if (isObjectOrSubjectInput) {
                    getStudentAnswersRequest();
                } else {
                    for (StudentAnswersLastModifiedTime studentModifiedTime : studentAnswersLastModifiedTimes) {
                        Student student = mStudentMap.get(studentModifiedTime
                                .getStudentId());
                        if (student != null) {
                            student.setLastModifiedTime(studentModifiedTime
                                    .getLastModifiedTime());
                        }
                    }
                }
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07071_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07072_000012E);
            } else if (resultCode.equals(ResultCode.result_200001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07073_200001E);
            } else if (resultCode.equals(ResultCode.result_200003E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07074_200003E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07075_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                isDataChange = true;
                if (mReadCardInfoDialog != null) {
                    mReadCardInfoDialog.dismiss();
                    mReadCardInfoDialog = null;
                }
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_070799_999999E);
            } else if (resultCode.equals(ResultCode.result_300017E.resultCode)) {
                MyToast.showShort(mContext, "请录入标准答案");
            } else {
                // TODO
                MyToast.showShort(mContext, "提交失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            LoadDialog.dismiss(mLoadDialog);
            LoadDialog.dismiss(ObjectAnswerActivity.mLoadDialog);
            LoadDialog.dismiss(SubjectAnswerActivity.mLoadDialog);
            isDataChange = false;
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                if (isSingleUpload) {
                    Student uploadStudent = uploadStudents.getFirst();
                    uploadStudent.setUploadStatus(FragmentStudentAdapter.UPLOAD_FAILURE);
                    uploadStudents.removeFirst();
                    mAdapter.notifyDataSetChanged();
                } else {
                    MyToast.showShort(mContext, "提交学生答案失败！");
                }
            }
        }
    }

    private void uploadStudentAnswerExaminationErrorListener(VolleyError error, String isObjectAnswer) {
//        isBackAndSave = false;
//        setIsAllUploadSucess();
        if (isSingleUpload) {
            Student uploadStudent = uploadStudents
                    .getFirst();
            uploadStudent
                    .setUploadStatus(FragmentStudentAdapter.UPLOAD_FAILURE);
            mAdapter.notifyDataSetChanged();
            uploadStudents.removeFirst();
            if (isObjectAnswer.equals("1")) {
                mRequest.disposeError(mContext,
                        mLoadDialog, error, "上传学生答案失败");
                mRequest.disposeError(mContext,
                        ObjectAnswerActivity.mLoadDialog, error, "上传学生答案失败");
                mRequest.disposeError(mContext,
                        SubjectAnswerActivity.mLoadDialog, error, "上传学生答案失败");
            } else if (isObjectAnswer.equals("2")) {
                mRequest.disposeError(mContext,
                        mLoadDialog, error, "录入学生分数失败");
                mRequest.disposeError(mContext,
                        ObjectAnswerActivity.mLoadDialog, error, "录入学生分数失败");
                mRequest.disposeError(mContext,
                        SubjectAnswerActivity.mLoadDialog, error, "录入学生分数失败");
            }
        } else {
            if (isObjectAnswer.equals("1")) {
                mRequest.disposeError(mContext,
                        mLoadDialog, error, "上传学生答案失败");
                mRequest.disposeError(mContext,
                        ObjectAnswerActivity.mLoadDialog, error, "上传学生答案失败");
                mRequest.disposeError(mContext,
                        SubjectAnswerActivity.mLoadDialog, error, "上传学生答案失败");
            } else if (isObjectAnswer.equals("2")) {
                mRequest.disposeError(mContext,
                        mLoadDialog, error, "录入学生分数失败");
                mRequest.disposeError(mContext,
                        ObjectAnswerActivity.mLoadDialog, error, "录入学生分数失败");
                mRequest.disposeError(mContext,
                        SubjectAnswerActivity.mLoadDialog, error, "录入学生分数失败");
            }
        }
    }

    /**
     * 弹出读卡的提示 如果蓝牙或者usb串口已经连接，则弹出提示，等待读卡
     */
    public void showReadCardPrompt() {
        if (!(mMarkingMenuActivity.mBluetoothHelper.isConn)) {
            return;
        }
        StringBuilder sb = new StringBuilder("当前已经连接阅卷机，请读卡!");
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("当前已经连接阅卷机，请读卡！");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 弹出读卡的信息
     */
    public void showReadCardInfo(Student student) {
        if (mReadCardInfoDialog == null) {
            if (mConnectedDialog != null) {
                mConnectedDialog.dismiss();
            }
            mReadCardInfoDialog = new ReadCardInfoDialog(mMarkingMenuActivity,
                    mClassManages, mRecordList);
            mReadCardInfoDialog
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            if (mReadCardInfoDialog != null) {
                                mReadCardInfoDialog.isCountDown = false;
                                mReadCardInfoDialog.mCountDown = -1;
                                mReadCardInfoDialog = null;
                            }
                        }
                    });
            mReadCardInfoDialog.setCancelable(false);
            mReadCardInfoDialog.setCanceledOnTouchOutside(false);
            mReadCardInfoDialog.show();
        }
        mReadCardInfoDialog.setData(student);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.d("hidden：" + hidden);
        if (!hidden && isRefresh) {
            configWidget();
//            mRefreshListener.onRefresh();
        }
        if (hidden) {// hidden为false ：隐藏
            mStuReadCardBt.setText("读卡");
            mMarkingMenuActivity.mReadFlag = mMarkingMenuActivity.NOT_READ_FLAG;
        } else {
            readCard(1, false);

        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == mMarkingMenuActivity.RESULT_OK) {
            if (requestCode == 0x210 || requestCode == 0x220) {
                if (data.getBooleanExtra(IntentUtil.SINGLE_UPLOAD, false)) {
                    mRefreshListener.onRefresh();
                }
            }
        }
    }

    /**
     * 完成读卡
     */
    public void readComplete(Map<String, Object> map) {
        if (map == null) {
            String msg = "读取答题卡失败!";
            mMarkingMenuActivity.record(msg, RecordType.read_card_failure);
            mMarkingMenuActivity.record("读取答题卡失败，点击查看帮助!",
                    RecordType.read_failure_help);
            showReadCardInfo(null);
            mMarkingMenuActivity.sendCommandForBackward();
            return;
        }
        String paperTypeText = (String) map.get("type");
        String studentNo = (String) map.get("student_id");
        Student readStudentFailuer = new Student();
        if (studentNo == null || studentNo.contains("*")
                || studentNo.contains("[")) {
            mMarkingMenuActivity.record("读取学号失败:" + studentNo,
                    RecordType.read_student_id_failure);
            mMarkingMenuActivity.record("读取学号失败，点击查看帮助!",
                    RecordType.read_studen_id_failure_help);
            readStudentFailuer.setNumber(studentNo);
            showReadCardInfo(readStudentFailuer);
            mMarkingMenuActivity.sendCommandForBackward();
            return;
        }

        Student student = null;
        for (ClassManage c : mClassManages) {
            if (c.getStudents() == null) {
                continue;
            }
            for (Student s : c.getStudents()) {
                if (s.getNumber().equals(studentNo)) {
                    student = s;
                    break;
                }
            }
            if (student != null) {
                break;
            }
        }
        if (student == null) {
            mMarkingMenuActivity.record("没有找到学号：" + studentNo,
                    RecordType.not_found_student_id);
            mMarkingMenuActivity.record("没有找到学号，点击查看帮助!",
                    RecordType.not_found_student_id_help);
            readStudentFailuer.setNumber(studentNo);
            showReadCardInfo(readStudentFailuer);
            mMarkingMenuActivity.sendCommandForBackward();
            return;
        }
        List<Map<String, Object>> stuAnswerList = AnswerUtil.mapToList(map,
                mTopics);
        String stuAnswerStr = AnswerUtil.listToStudentAnswer(stuAnswerList,
                TopicUtil.getCurrentMaxNo(mTopics));
        float studentGrade = 0;
        if (!mMarkingMenuActivity.mExamination.getPaperType().equals(
                PaperType.AB.text)) {// 不分AB卷
            studentGrade = AnswerUtil.getStudentGrade(mTopics, mStaList,
                    stuAnswerList);
        } else if (paperTypeText != null
                && paperTypeText.equals(PaperType.A.text)) {
            studentGrade = AnswerUtil.getStudentGrade(mTopics, mStaList,
                    stuAnswerList);
        } else if (paperTypeText != null
                && paperTypeText.equals(PaperType.B.text)) {
            studentGrade = AnswerUtil.getStudentGrade(mTopics, mStaList,
                    stuAnswerList);
        }
        student.getAnswer().setObjectAnswers(stuAnswerStr);
        // student.getAnswer().setSubjectScores(0f);
        student.getAnswer().setObjectScores(studentGrade);

        if (mMarkingMenuActivity.mExamination.getPaperType().equals(
                PaperType.NONE.text)) {
            student.getAnswer().setPaperType(PaperType.NONE.text);
        } else {// TODO AB卷，读取答题卡上的AB卷类型
            student.getAnswer().setPaperType(PaperType.A.text);
        }
        student.getAnswer().setEffectDate(
                DateFormatUtil.convertMillisecondsToStr(
                        System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        float totalScore = student.getAnswer().getObjectScores()
                + student.getAnswer().getSubjectScores();
        student.getAnswer().setScores(totalScore);
        student.setStatus(StudentStatus.I.text);
        student.setIsReadCard("1");
        // 设置数据学生列表
        setListData(mClassManages);
        mStudent = student;
        mBackupStudent = (Student) mStudent.deepCopy();
        // 设置数据，学生详细答案
//        if (mFragmentReadSub != null) {
        // mFragmentReadSub.setData(student);
//        }
        mMarkingMenuActivity.record(
                "读卡成功：" + student.getName() + " " + student.getNumber(),
                RecordType.read_card_success);
        showReadCardInfo(student);
        // 去上传
        // uploadStudentAnswerRequest(mClassManages);
        uploadSingleStudentAnswerRequest(student, false, "1", true);
        mMarkingMenuActivity.sendCommandForForward();
    }
}